const http = require('../../../utils/http.js');

Page({
    data: {
        base_candidate_info: {
            id_number: '',
            phone: '',
            name: '',
            gender: '',
            birth_date: '',
            ethnicity_id: '',
            foreign_language_id: '',
            political_status_id: ''
        },
        ck_academic_info: {
            education_level: '',
            diploma_number: '',
            graduation_type: '',
            graduation_school: '',
            graduation_date: '',
            job_category: '',
            is_working: '',
            work_location: '',
            work_name: '',
            work_start_date: ''
        },
        zk_exam_info: {
            idNumber: '',
            // 四个下拉框字段对应的code
            candidate_category_id: '', // 考生类别 id
            candidate_category_code: '', // 考生类别 code
            candidate_type_id: '',     // 考生类型 id
            candidate_type_code: '',     // 考生类型 code
            registration_site_id: '',  // 报名点 id
            registration_site_code: '',  // 报名点 code
            graduation_school_id: '',   // 毕业学校 id
            graduation_school_code: '',   // 毕业学校 code

            // 其他输入字段
            schooling_length: '',   // 学制
            mailing_address: '',    // 通讯地址
            postal_code: '',        // 邮政编码
            specialskills: '',      // 特长
            work_school_code: '',   // 工作单位代码
            junior_position: ''     // 职务
        },
        exam_site_info: {
            code: '',
            name: '',
            address: ''
        },
        expanded: {
            base: false,
            academic: false,
            exam: false
        },
        idToNameMappings: {
            ethnicity: {},         // 民族映射
            politicalstatus: {},   // 政治面貌映射
            foreignlanguage: {},  // 外语语种映射
            CKeducation: {},
            graduationType: {},
            CKoccupation: {},
            CKschool: {},
            examType: {},
            outsideResidence: {},
            militaryService: {},
            candidateFeature: {},
            admissionCategory: {},
            examLevel: {},
            examSubject: {},
            studyLocation: {},
            studyMode: {},
            examUniversity: {},
            CKMajor: {},
            candidateCategory: {},  // 考生类别映射
            candidateType: {},      // 考生类型映射
            examSite: {},           // 报名点映射
            graduationSchool: {}    // 毕业学校映射
        }
    },
    formatDate(dateString) {
        if (!dateString) return '';

        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');

        return `${year}-${month}-${day}`;
    },
    onLoad() {
        try {
            const baseInfo = wx.getStorageSync('base_candidate_info');
            const academicInfo = wx.getStorageSync('ck_academic_info');
            const examInfo = wx.getStorageSync('zk_exam_info');

            if (baseInfo) {
                baseInfo.birth_date = this.formatDate(baseInfo.birth_date);
                this.setData({ base_candidate_info: baseInfo });
            }

            if (academicInfo) {
                this.setData({ ck_academic_info: academicInfo });
            }

            if (examInfo) {
                // 映射文档2中的字段到当前页面结构
                const mappedExamInfo = {
                    candidate_category_id: examInfo.candidate_category_id,
                    candidate_category_code: examInfo.candidate_category_code,
                    candidate_type_id: examInfo.candidate_type_id,
                    candidate_type_code: examInfo.candidate_type_code,
                    registration_site_id: examInfo.registration_site_id,
                    registration_site_code: examInfo.registration_site_code,
                    graduation_school_id: examInfo.graduation_school_id,
                    graduation_school_code: examInfo.graduation_school_code,
                    schooling_length: examInfo.schooling_length,
                    mailing_address: examInfo.mailing_address,
                    postal_code: examInfo.postal_code,
                    specialskills: examInfo.specialskills,
                    work_school_code: examInfo.work_school_code,
                    junior_position: examInfo.junior_position
                };

                this.setData({
                    zk_exam_info: {
                        ...this.data.zk_exam_info,
                        ...mappedExamInfo
                    }
                });

                if (examInfo.registration_site_id) {
                    this.getExamSiteInfo(examInfo.registration_site_id);
                }
            }

            this.fetchNameMappings();
        } catch (error) {
            console.error('Error loading candidate info from storage:', error);
        }
    },
    fetchNameMappings() {
        const mappingFields = {
            ethnicity: 'ethnicity_id',         // 民族
            politicalstatus: 'political_status_id',   // 政治面貌
            foreignlanguage: 'foreign_language_id',  // 外语语种
            CKeducation: 'education_level',
            graduationType: 'graduation_type',
            CKoccupation: 'job_category',
            CKschool: 'graduation_school',
            examType: 'exam_type',
            outsideResidence: 'outside_residence',
            militaryService: 'military_service',
            candidateFeature: 'candidate_feature',
            admissionCategory: 'admission_category',
            examLevel: 'exam_level',
            examSubject: 'exam_subject',
            studyLocation: 'study_location',
            studyMode: 'study_mode',
            examUniversity: 'ck_exam_university_school',
            CKMajor: 'ck_major',
            candidateCategory: 'candidate_category_id',  // 考生类别
            candidateType: 'candidate_type_id',           // 考生类型
            examSite: 'registration_site_id',             // 报名点
            graduationSchool: 'graduation_school_id'      // 毕业学校
        };

        const promises = [];

        Object.keys(mappingFields).forEach((field) => {
            const fieldId = mappingFields[field];
            const ids = this.getUniqueIds(fieldId);

            if (ids.length === 0) return;

            ids.forEach((id) => {
                let url = '';
                if (field === 'ethnicity') {
                    url = `/ethnicity/info?id=${id}`; // 民族特殊处理
                } else if (field === 'politicalstatus') {
                    url = `/politicalstatus/info?id=${id}`; // 政治面貌特殊处理
                } else if (field === 'foreignlanguage') {
                    url = `/foreignlanguage/info?id=${id}`; // 外语语种特殊处理
                } else {
                    url = `/chengkao/${field}/${id}`; // 其他字段通用处理
                }

                const promise = http.get(url).then((res) => {
                    if (res.statusCode === 200) {
                        const newName = res.data.data.name || '未知';
                        this.setData({
                            [`idToNameMappings.${field}.${id}`]: newName
                        });
                    } else {
                        console.error(`Error fetching ${field} info for id ${id}:`, res.data.message);
                    }
                }).catch((err) => {
                    console.error(`Error fetching ${field} info for id ${id}:`, err);
                });

                promises.push(promise);
            });
        });

        Promise.all(promises).then(() => {
            console.log('All mappings fetched successfully.');
        }).catch((err) => {
            console.error('Error fetching all mappings:', err);
        });
    },
    getUniqueIds(fieldId) {
        const ids = new Set();
        const { base_candidate_info, ck_academic_info, zk_exam_info } = this.data;

        [base_candidate_info, ck_academic_info, zk_exam_info].forEach((info) => {
            if (info[fieldId]) {
                ids.add(info[fieldId]);
            }
        });

        return Array.from(ids);
    },
    getExamSiteInfo(siteId) {
        http.get(`/chengkao/examSite/${siteId}`).then((res) => {
            if (res.statusCode === 200) {
                this.setData({
                    exam_site_info: {
                        code: res.data.data.code || '',
                        name: res.data.data.name || '',
                        address: res.data.data.address || ''
                    }
                });
            } else {
                console.error(`Error fetching exam site info for id ${siteId}:`, res.data.message);
            }
        }).catch((err) => {
            console.error(`Error fetching exam site info for id ${siteId}:`, err);
        });
    },
    toggleSection(e) {
        const { section } = e.currentTarget.dataset;
        this.setData({
            [`expanded.${section}`]: !this.data.expanded[section]
        });
    },
    navigateToEdit(e) {
        const { section } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/chengkao/chengkao_page${section}/chengkao_page${section}`
        });
    }
});